import 'dart:convert';
import 'package:flutter/widgets.dart';
import '../public.dart';

class SMSCode extends StatefulWidget {
  final String phone;
  final String dialCode;
  final Function callback;
  final Map<String, dynamic> options;
  SMSCode(this.phone,
      {Key key,
      this.dialCode,
      this.callback,
      this.options = const {'ratio': 0.6, 'service': 'qmmh'}})
      : super(key: key);

  @override
  _SMSCodeState createState() => _SMSCodeState();
}

class _SMSCodeState extends State<SMSCode> {
  @override
  void initState() {
    super.initState();
    requestHanddle();
  }

  SmsCodeModel smsCode;
  List<Offset> postion = [];
  double width = 0;
  double height = 0;
  bool isDisable = true;

  _onTapUp(TapUpDetails e) {
    if (postion.length < 2) {
      postion.add(e.localPosition);
    }
    if (postion.length >= 2) {
      isDisable = false;
    }
    setState(() {});
    LogUtil.e(e, tag: '_onTapUp');
  }

  requestHanddle([bool isRefresh = false, String imgCode]) {
    UserService.sendsms({
      'mobile': widget.phone,
      'service': widget.options['service'],
      'countryCode': widget.dialCode,
      'imgCode': imgCode ?? '',
      'refresh': 0
    }).then((res) {
      if (isRefresh) {
        isDisable = true;
        postion = [];
      }
      if (res['status'] == 1031) {
        smsCode = res['data'];
        double ratio = widget.options['ratio'];
        width = smsCode.width * ratio;
        height = smsCode.height * ratio;
        setState(() {});
        return null;
      }
      Navigator.pop(context);
      if (res['status'] == 0) {
        if (widget.callback != null) {
          widget.callback();
        } else {
          LogUtil.e('必须提供callback方法');
        }
      } else {
        ACGN.toast.message(res['msg']);
      }
    }).catchError((err) {
      LogUtil.e(err);
    });
  }

  List<Widget> _setPostion() {
    List<Widget> list = [];
    postion.asMap().forEach((index, item) {
      list.add(Positioned(
        top: item.dy,
        left: item.dx,
        child: Container(
            width: 16,
            height: 16,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: ColorUtil.rgba(131, 218, 53),
                borderRadius: BorderRadius.all(Radius.circular(8))),
            child: Text(
              '${index + 1}',
              style: TextStyle(color: Colors.white, fontSize: 12),
            )),
      ));
    });
    return list;
  }

  _refreshHanddle() {
    requestHanddle(true);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: LoadingComponent(
            show: smsCode == null,
            padding: EdgeInsets.all(10),
            testStyle: TextStyle(color: Colors.black45),
            child: Column(children: [
              Container(
                  padding: EdgeInsets.all(10),
                  child: Container(
                      width: width,
                      height: height,
                      child: Stack(
                        children: [
                          GestureDetector(
                              onTapUp: _onTapUp,
                              child: smsCode?.image != null
                                  ? Image.memory(
                                      smsCode.image,
                                      fit: BoxFit.contain,
                                      width: width,
                                      height: height,
                                    )
                                  : SizedBox.shrink()),
                          ..._setPostion(),
                          Positioned(
                              bottom: 0,
                              right: 0,
                              child: GestureDetector(
                                  onTap: _refreshHanddle,
                                  child: Container(
                                      decoration: BoxDecoration(
                                          color: ColorUtil.rgba(0, 0, 0, 0.5),
                                          borderRadius: BorderRadius.only(
                                              topLeft: Radius.circular(4))),
                                      padding: EdgeInsets.all(4),
                                      child: SVG.icon('refresh',
                                          color: Colors.white))))
                        ],
                      ))),
              Container(
                  padding: EdgeInsets.all(10),
                  child: Row(children: [
                    Expanded(
                        child: Text(
                      '请在上图中点击正确的示例文字:',
                      style: TextStyle(color: Colors.black54, fontSize: 14),
                    )),
                    Container(
                        child: Text(
                          smsCode?.content ?? '',
                          style: TextStyle(
                              color: ColorUtil.rgba(200, 0, 0), fontSize: 24),
                        ),
                        padding: EdgeInsets.only(left: 8, right: 8),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                ColorUtil.rgba(255, 129, 116),
                                ColorUtil.rgba(255, 206, 112),
                              ],
                            )))
                  ])),
              Container(
                  width: double.infinity,
                  child: FlatButton(
                    height: 56,
                    textColor: Colors.black54,
                    disabledTextColor: Colors.black12,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(0),
                      side: BorderSide.none,
                    ),
                    child: Text(
                      '确定',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                    ),
                    onPressed: isDisable
                        ? null
                        : () {
                            if (postion.length >= 2) {
                              isDisable = !isDisable;
                              double ratio = widget.options['ratio'];
                              requestHanddle(
                                  true,
                                  jsonEncode({
                                    "appId": "",
                                    "fontPoints": [
                                      {
                                        "x": postion[0].dx ~/ ratio,
                                        "y": postion[0].dy ~/ ratio
                                      },
                                      {
                                        "x": postion[1].dx ~/ ratio,
                                        "y": postion[1].dy ~/ ratio
                                      }
                                    ],
                                    "userIdentifier": widget.phone,
                                    "verificaType": 2
                                  }));
                            }
                          },
                  ),
                  decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(
                              color: Colors.black12,
                              width: 1,
                              style: BorderStyle.solid))))
            ])));
  }
}
